import * as amqp from "amqplib";
// RabbitMQ 服务器的连接信息
const rabbitMQServer = "amqp://mingcai_mq:EUDNfpZRbhfjb8PZ@95.169.25.181";


// RabbitMQ 服务器的连接信息

// 定义订单阶段主题
enum OrderStage {
    Created = "order.created",
    Paid = "order.paid",
    Shipped = "order.shipped",
}
enum PaymentStage {
    Success = "payment.success",
}

enum InventoryStage {
    Success = "inventory.success",
}

// 订单消息数据格式
interface OrderMessage {
    orderId: string;
    stage: OrderStage | PaymentStage | InventoryStage;
    // 其他订单信息字段...
}

async function sendOrderMessage(orderMessage: OrderMessage, channel: amqp.Channel, exchangeName: string) {
    try {
        // 将订单消息按阶段发布到主题交换机
        channel.publish(
            exchangeName,
            orderMessage.stage,
            Buffer.from(JSON.stringify(orderMessage))
        );
        console.log(`[x] Sent order message - Order ID: ${orderMessage.orderId}, Stage: ${orderMessage.stage}`);


    } catch (error) {
        console.error("Error in sendOrderMessage:", error);
    }
}

async function main() {
    // 创建 RabbitMQ 连接
    const connection = await amqp.connect(rabbitMQServer);
    const channel = await connection.createChannel();

    // 定义交换机名称
    const exchangeName = 'topic_exchange';

    // 声明主题交换机
    const type = "topic";
    await channel.assertExchange(exchangeName, type, {durable: false});
    const orderId = `${new Date().getTime()}`
    // 示例用法
    let taskList = [
        {
            orderId: orderId,
            stage: OrderStage.Created,
            // 其他订单信息...
        },
        {
            orderId: orderId,
            stage: OrderStage.Paid,
            // 其他订单信息...
        },
        {
            orderId: orderId,
            stage: OrderStage.Shipped,
            // 其他订单信息...
        },
        {
            orderId: orderId,
            stage: PaymentStage.Success,
            // 其他订单信息...
        },
        {
            orderId:orderId,
            stage: InventoryStage.Success,
            // 其他订单信息...
        }
    ]

    for (const item of taskList) {
        // 发送配送订单消息
       await sendOrderMessage(item, channel, exchangeName);
    }


    // 关闭连接
    setTimeout(() => {
        connection.close();
        process.exit(0);
    }, 500);
}

main()

